<template>
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    :width="dialogWidth"
    draggable
    :destroy-on-close="true"
    :close-on-press-escape="false"
    @closed="closeDialog"
  >
    <div v-if="active === 0">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="110px"
      >
        <el-form-item label="工厂" prop="plantId">
          <el-select
            v-model="formData.plantId"
            placeholder="请选择工厂"
            @change="PlanChange"
            style="width: 250px"
          >
            <el-option
              v-for="item in plants"
              :key="item.plantId"
              :label="item.plantName"
              :value="item.plantId"
            />
          </el-select>
        </el-form-item>

        <!--        <el-form-item label="物料">-->
        <!--          <el-input-->
        <!--            v-model="formData.materialName"-->
        <!--            style="width: 250px"-->
        <!--            disabled-->
        <!--          />-->
        <!--        </el-form-item>-->

        <!--        <el-form-item label="计划到货日期">-->
        <!--          <el-input-->
        <!--            v-model="formData.arriveDate"-->
        <!--            style="width: 250px"-->
        <!--            disabled-->
        <!--          />-->
        <!--        </el-form-item>-->

        <el-form-item label="交货地点" prop="inboundStorageLocationId">
          <el-select
            v-model="formData.inboundStorageLocationId"
            placeholder="请选择交货地点"
            style="width: 250px"
            clearable
          >
            <el-option
              v-for="item in storageLocations"
              :key="item.id"
              :label="item.storageLocationName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="到货日期" prop="arriveTime">
          <el-date-picker
            v-model="formData.arriveTime"
            type="date"
            placeholder="请选择到货日期"
            style="width: 250px"
          />
        </el-form-item>

        <!--        <el-form-item label="实际交货地点">-->
        <!--          <el-input-->
        <!--            v-model="formData.storageLocationName"-->
        <!--            style="width: 250px"-->
        <!--          />-->
        <!--        </el-form-item>-->

        <el-form-item label="时间窗" prop="arriveTimeWindowCode">
          <el-select
            v-model="formData.arriveTimeWindowCode"
            placeholder="请选择时间窗"
            style="width: 250px"
            clearable
          >
            <el-option
              v-for="item in timeWindows"
              :key="item.id"
              :label="item.arriveTimeWindowCode"
              :value="item.arriveTimeWindowCode"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <!-- </el-card> -->
    <!-- <el-card v-if="active === 1" class="transfer-card-class"> -->
    <div v-if="active === 1" class="transfer-card-class u-flex">
      <div>
        <el-divider content-position="left">待发货箱标签清单</el-divider>
        <div class="mb-[10px]">
          <span style="font-weight: 600; font-size: 14px; margin-left: 20px"
            >物料</span
          ><el-select
            v-model="selectedMaterail"
            placeholder="选择物料"
            clearable
            style="margin-left: 20px"
          >
            <el-option
              v-for="item in materials"
              :key="item.materialId"
              :label="item.materialName"
              :value="item.materialId"
            />
          </el-select>
          <el-button type="primary" class="ml-[20px]" @click="findMaterails()"
            >筛选</el-button
          >
        </div>
        <el-table
          :data="leftList"
          :height="498"
          highlight-current-row
          :header-cell-style="{ backgroundColor: '#F0F8FF' }"
          border
          @selection-change="leftChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column
            prop="materialNumber"
            label="物料编号"
            align="center"
            min-width="120"
            show-overflow-tooltip
          />
          <el-table-column
            prop="materialName"
            label="物料名称"
            align="center"
            min-width="150"
            show-overflow-tooltip
          />
          <el-table-column
            prop=""
            label="包装条码"
            align="center"
            min-width="150"
            show-overflow-tooltip
          />
          <el-table-column
            prop="supplyBatch"
            label="生产批次"
            align="center"
            min-width="150"
            show-overflow-tooltip
          />
          <el-table-column
            prop="materialQuantity"
            label="包装容量"
            align="center"
            min-width="100"
            show-overflow-tooltip
          />
        </el-table>
      </div>

      <div class="mid-button-class">
        <div>
          <p>
            <el-button type="primary" @click="rightAdd" :disabled="addDisabled"
              >添加<i-ep-ArrowRight
            /></el-button>
          </p>
          <p>
            <el-button
              type="primary"
              @click="rightRemove"
              :disabled="removeDisabled"
              ><i-ep-ArrowLeft />移除</el-button
            >
          </p>
        </div>
      </div>
      <div>
        <el-divider content-position="left">待发货箱标签清单</el-divider>
        <el-table
          :data="data"
          :height="538"
          highlight-current-row
          :header-cell-style="{ backgroundColor: '#F0F8FF' }"
          border
          @selection-change="rightChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column
            prop="materialNumber"
            label="物料编号"
            align="center"
            min-width="120"
            show-overflow-tooltip
          />
          <el-table-column
            prop="materialName"
            label="物料名称"
            align="center"
            min-width="150"
            show-overflow-tooltip
          />
          <el-table-column
            prop=""
            label="包装条码"
            align="center"
            min-width="150"
            show-overflow-tooltip
          />
          <el-table-column
            prop="supplyBatch"
            label="生产批次"
            align="center"
            min-width="150"
            show-overflow-tooltip
          />
          <el-table-column
            prop="materialQuantity"
            label="包装容量"
            align="center"
            min-width="100"
            show-overflow-tooltip
          />
        </el-table>
      </div>
    </div>
    <!-- </el-card> -->
    <template #footer>
      <div class="dialog-footer">
        <el-button v-if="active === 0" type="primary" @click="next"
          >创建送货单并继续</el-button
        >
        <el-button v-if="active === 1" @click="back">上一步</el-button>
        <el-button v-if="active === 1" type="primary" @click="handleSubmit"
          >保存</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "SRMDELIVERYEIDT",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);
const active = ref(0);
const dialogWidth = ref("430px");

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  stepActive: {
    type: Number,
    default: () => {
      return 0;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    if (newVal) {
      active.value = props.stepActive;
    }
  }
);

// 表单校验规则
const rules = reactive({
  plantId: [{ required: true, message: "未选择工厂", trigger: "change" }],
  arriveTime: [
    {
      required: true,
      type: "date",
      message: "未选择到货日期",
      trigger: "change",
    },
  ],
  inboundStorageLocationId: [
    { required: true, message: "未选择要货地点", trigger: "change" },
  ],
  arriveTimeWindowCode: [
    { required: true, message: "未选择采购协议", trigger: "change" },
  ],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  organizationId: "",
  organizationCode: "",
  organizationName: "",
  plantId: "",
  plantCode: "",
  plantName: "",
  purchasePlanNumber: "",
  partnerId: "",
  partnerCode: "",
  materialId: "",
  materialNumber: "",
  materialName: "",
  inboundStorageLocationId: "",
  inboundStorageLocationCode: "",
  inboundStorageLocationName: "",
  arriveTime: "",
  arriveYear: "",
  arriveMonth: "",
  arriveWeek: "",
  purchasingCycleType: "",
  planQuantity: 0,
  agreeQuantity: "",
  unitCode: "",
  replyUserId: "",
  replyUserName: "",
  replyTime: "",
  replyContent: "",
  orderScheduleState: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  deleted: "",
  beginDate: "",
  endDate: "",
  details: [],
  deliveryCode: "",
  arriveTimeWindowCode: "",
  arriveTimeWindowBegin: "",
  arriveTimeWindowEnd: "",
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        organizationId,
        organizationCode,
        organizationName,
        plantId,
        plantCode,
        plantName,
        purchasePlanNumber,
        partnerId,
        partnerCode,
        materialId,
        materialNumber,
        materialName,
        storageLocationId,
        storageLocationCode,
        storageLocationName,
        arriveDate,
        arriveYear,
        arriveMonth,
        arriveWeek,
        purchasingCycleType,
        planQuantity,
        agreeQuantity,
        unitCode,
        replyUserId,
        replyUserName,
        replyTime,
        replyContent,
        orderScheduleState,
        remarks,
        createTime,
        createdUserId,
        lastUpdateTime,
        lastUpdatedUserId,
        deleted,
        beginDate,
        endDate,
      } = newVal;
      Object.assign(formData, {
        id,
        organizationId,
        organizationCode,
        organizationName,
        plantId,
        plantCode,
        plantName,
        purchasePlanNumber,
        partnerId,
        partnerCode,
        materialId,
        materialNumber,
        materialName,
        storageLocationId,
        storageLocationCode,
        storageLocationName,
        arriveDate,
        arriveYear,
        arriveMonth,
        arriveWeek,
        purchasingCycleType,
        planQuantity,
        agreeQuantity,
        unitCode,
        replyUserId,
        replyUserName,
        replyTime,
        replyContent,
        orderScheduleState,
        remarks,
        createTime,
        createdUserId,
        lastUpdateTime,
        lastUpdatedUserId,
        deleted,
        beginDate,
        endDate,
      });
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  dialogWidth.value = "420px";
  emit("change-visible", false);
  materials.value = [];
  storageLocations.value = [];
  resetForm();
}

/** 重置表单 */
function resetForm() {
  // formRef.value.resetFields();
  // formRef.value.clearValidate();
  formData.id = "";
  formData.organizationId = "";
  formData.organizationCode = "";
  formData.organizationName = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.plantName = "";
  formData.purchasePlanNumber = "";
  // formData.partnerId = "";
  formData.partnerCode = "";
  formData.materialId = "";
  formData.materialNumber = "";
  formData.materialName = "";
  formData.inboundStorageLocationId = "";
  formData.inboundStorageLocationCode = "";
  formData.inboundStorageLocationName = "";
  formData.arriveTime = "";
  formData.arriveYear = "";
  formData.arriveMonth = "";
  formData.arriveWeek = "";
  formData.purchasingCycleType = "";
  formData.planQuantity = 0;
  formData.agreeQuantity = "";
  formData.unitCode = "";
  formData.replyUserId = "";
  formData.replyUserName = "";
  formData.replyTime = "";
  formData.replyContent = "";
  formData.orderScheduleState = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.deleted = "";
  formData.beginDate = "";
  formData.endDate = "";
  formData.arriveTimeWindowCode = "";
  formData.arriveTimeWindowBegin = "";
  formData.arriveTimeWindowEnd = "";
  selectedMaterail.value = "";
  leftList.value = [];
  leftAllList.value = [];
}

const loading = ref(false);

function next() {
  //下一步前进行工厂校验
  formRef.value.validate().then(async (res: any) => {
    if (res) {
      active.value++;
      dialogWidth.value = "1650px";
    }
  });
}

function back() {
  active.value--;
  dialogWidth.value = "420px";
}

/** 用户信息保存提交 */
async function handleSubmit() {
  if (data.value.length <= 0) {
    ElMessage.error("请选择要发货的包装");
    return;
  }
  storageLocations.value.forEach((item: any) => {
    if (item.id == formData.inboundStorageLocationId) {
      formData.inboundStorageLocationCode = item.storageLocationCode;
      formData.inboundStorageLocationName = item.storageLocationName;
    }
  });
  timeWindows.value.forEach((item: any) => {
    if (item.arriveTimeWindowCode == formData.arriveTimeWindowCode) {
      formData.arriveTimeWindowBegin = item.arriveTimeWindowBegin;
      formData.arriveTimeWindowEnd = item.arriveTimeWindowEnd;
    }
  });
  formData.details = data.value;
  console.log(formData.arriveTimeWindowCode);
  await request({
    url: "/srm/partner/deliverynote/save",
    method: "post",
    data: formData,
  });
  ElMessage.success(`保存成功`);
  closeDialog();
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
// 工厂
let plants: any = ref([]);
// 要货地点
let storageLocations: any = ref([]);
//时间窗
let timeWindows: any = ref([]);
// ---------------------------------------- 穿梭框部分 start ---------------------------------------------
// 右侧表格的数据
const data = ref([]);
const leftList = ref([]);
const leftAllList = ref([]);
const materials = ref([]);
// 左侧的勾选的数据
const leftSelected = ref([]);
const addDisabled = ref(true);
const removeDisabled = ref(true);
const selectedMaterail = ref("");

onMounted(() => {
  //获取工厂
  getPartnerPlants();
  //获取时间窗
  getTimeWindows();
});

// 添加
function rightAdd() {
  if (!data.value) {
    data.value = [...leftSelected.value];
  } else {
    data.value = [...data.value, ...leftSelected.value];
  }
  data.value = unique(data.value, "id");
  // 添加后 删除左侧被选中的数据
  data.value.forEach((res) => {
    // console.log(res)
    leftList.value.forEach((item, index) => {
      if (item.id == res.id) {
        leftList.value.splice(index, 1);
      }
    });
    leftAllList.value.forEach((item, index) => {
      if (item.id == res.id) {
        leftAllList.value.splice(index, 1);
      }
    });
  });
}
// 左侧的勾选的数据
function leftChange(data) {
  leftSelected.value = data;
  if (leftSelected.value.length > 0) {
    addDisabled.value = false;
  } else {
    addDisabled.value = true;
  }
}

// 排序
watch(
  () => data.value,
  (data) => {
    data.sort(compare);
  }
);

// 左侧的勾选的数据
const rightList = ref([]);
// 选中右侧的数据
function rightChange(data) {
  rightList.value = data;
  if (rightList.value.length > 0) {
    removeDisabled.value = false;
  } else {
    removeDisabled.value = true;
  }
}
// 删除
function rightRemove() {
  rightList.value.forEach((item, index) => {
    data.value.forEach((res, oindex) => {
      if (res.id == item.id) {
        data.value.splice(oindex, 1);
      }
    });
    leftList.value.push(item);
  });
  leftList.value.sort(compare);
}

// 去重
function unique(arr, type) {
  const res = new Map();
  return arr.filter((a) => !res.has(a[type]) && res.set(a[type], 1));
}
// 排序方法
function compare(obj1, obj2) {
  var val1 = obj1.id;
  var val2 = obj2.id;
  if (val1 < val2) {
    return -1;
  } else if (val1 > val2) {
    return 1;
  } else {
    return 0;
  }
}
/** 筛选物料点击时间*/
function findMaterails() {
  if (selectedMaterail.value) {
    leftList.value = [];
    leftAllList.value.forEach((item, index) => {
      if (item.materialId == selectedMaterail.value) {
        leftList.value.push(item);
      }
    });
  } else {
    leftList.value = leftAllList.value;
  }
}
// ---------------------------------------- 穿梭框部分 end ---------------------------------------------
//获取供应商合作工厂
async function getPartnerPlants() {
  request({
    url: `/srm/partner/deliverynote/plant`,
    method: "get",
  }).then((data) => {
    plants.value = data.data;
  });
}
//选择工厂时根据工厂id查询存储地
async function PlanChange() {
  //清楚筛选 清空右侧待选
  selectedMaterail.value = "";
  data.value = [];
  //根据工厂id查询要货地点
  request({
    url: `/srm/core/storagelocation/getList`,
    method: "post",
    data: { plantId: formData.plantId },
  }).then((data) => {
    storageLocations.value = data.data;
  });
  // 根据所选工厂id和供应商id(后端获取)查询供应商发货包装信息
  request({
    url: `/srm/partner/deliverynote/getList`,
    method: "post",
    data: formData,
  }).then((value) => {
    leftList.value = value.data;
    leftAllList.value = value.data;
  });
  //根据供应商id(后端获取)查询存在协议工厂
  request({
    url: `/srm/partner/deliverynote/getMaterials`,
    method: "post",
    data: formData,
  }).then((value) => {
    materials.value = value.data;
  });
}
//时间窗查询
async function getTimeWindows() {
  request({
    url: `/srm/srmtimewindow/getList`,
    method: "post",
    data: formData,
  }).then((data) => {
    timeWindows.value = data.data;
  });
}
</script>

<style lang="scss" scoped>
.step-class {
  margin-bottom: 20px;
  padding: 0 28%;
}
.transfer-card-class {
  height: 600px;
  width: 1610px;
  margin: 0 20px;
}
.u-flex {
  display: flex;
}
.mid-button-class {
  margin: 0 20px;
  text-align: center;
  display: flex;
  align-items: center;
}
</style>
